//
//  LoginViewModel.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/17.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

import RxSwift

struct LoginViewModel {

    let username = Variable<String>("")
    let password = Variable<String>("")

    var isValid: Observable<Bool>

    init() {
        isValid = Observable.combineLatest(self.username.asObservable(),
                                           self.password.asObservable()) { (username, password) in
            return username.count > 0
                && password.count > 0
        }
    }
    
    func logIn(loginType: String = "1",
               phoneNo: String,
               captcha: String,
               userAccount: String = "",
               password: String = "",
               rememberMe: String = "",
               bag: DisposeBag) {
        Network.request(target:
            .logIn(loginType: loginType,
                   phoneNo: phoneNo,
                   captcha: captcha,
                   userAccount: userAccount,
                   password: password,
                   rememberMe: rememberMe),
        success: { (obj: LoginModel) in
            let tokenInfo = TokenInfo(accessToken: obj.token, refreshToken: obj.token)
            AppUser.current.update(tokenInfo: tokenInfo)
            MainCoordinator.shared.home()
        }, failure: { (moyaError) in
            EHToast.show(moyaError.localizedDescription)
        }, error: { (errorStr) in
            EHToast.show(errorStr)
        }, dispose: bag)
    }
}
